package com.situ.address.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.address.entity.Address;
import com.situ.address.mapper.AddressMapper;
import com.situ.address.service.IAddressService;
import com.situ.address.vo.LayuiTableVO;
import com.situ.address.vo.LayuiTreeVO;

@Service
public class AddressServiceImpl implements IAddressService {

	@Autowired
	private AddressMapper addressMapper;

	@Override
	public void saveAddress(String name, Integer parentId) {
		Address add = new Address();
		add.setName(name);
		add.setParentId(parentId);
		addressMapper.insert(add);
	}

	@Override
	public List<LayuiTreeVO> tree() {
		List<LayuiTreeVO> result = new ArrayList<>();
		// 先查国家
		List<Address> countrys = addressMapper.selectByParentId(0);
		for (Address a : countrys) {
			result.add(extendAddress(a));
		}
		return result;
	}

	private LayuiTreeVO extendAddress(Address address) {
		LayuiTreeVO vo = new LayuiTreeVO();
		vo.setTitle(address.getName());
		List<Address> subs = addressMapper.selectByParentId(address.getId());
		if (subs != null && !subs.isEmpty()) {// 如果当前地址有子地址
			vo.setChildren(new ArrayList<>());
			for (Address aaa : subs) {
				vo.getChildren().add(extendAddress(aaa));
			}
		}
		return vo;
	}

	@Override
	public LayuiTableVO tree2() {
		LayuiTableVO vo = new LayuiTableVO();
		List<Address> list = addressMapper.selectAll();
		vo.setData(list);
		vo.setCount(Long.valueOf(list.size()));
		return vo;
	}

}
